package handlers

import (
	"github.com/gin-gonic/gin"
	"golang-master/photo-gallery/models"
	"golang-master/photo-gallery/utils"
	"gorm.io/gorm"
	"net/http"
)

type AuthHandler struct {
	DB *gorm.DB
}

func NewAuthHandler(db *gorm.DB) *AuthHandler {
	return &AuthHandler{DB: db}
}

type RegisterInput struct {
	Username string `json:"username" binding:"required"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=6"`
}

type LoginInput struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func (h *AuthHandler) Register(c *gin.Context) {
	var input RegisterInput

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查用户名是否已存在
	var existingUser models.User
	if err := h.DB.Where("username = ?", input.Username).First(&existingUser).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{
			"code": 409,
			"msg":  "Username already exists",
			"data": ""})
		return
	}

	// 加密密码
	hashedPassword, err := utils.HashPassword(input.Password)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "Failed to hash password",
			"data": ""})
		return
	}

	// 创建新用户
	user := models.User{
		Username: input.Username,
		Email:    input.Email,
		Password: hashedPassword,
	}

	if err := h.DB.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "Failed to create user",
			"data": "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": user.ID,
	})
}

func (h *AuthHandler) Login(c *gin.Context) {
	var input LoginInput

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user models.User
	if err := h.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 500,
			"msg":  "Invalid username",
			"data": ""})
		return
	}

	if !utils.CheckPasswordHash(input.Password, user.Password) {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 500,
			"msg":  "Invalid Password",
			"data": ""})
		return
	}

	// 创建会话
	session, _ := utils.Store.Get(c.Request, "photo-session")
	session.Values["user_id"] = user.ID
	session.Save(c.Request, c.Writer)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Login successful",
		"data": gin.H{
			"user_id": user.ID,
		},
	})
}

func (h *AuthHandler) Logout(c *gin.Context) {
	session, _ := utils.Store.Get(c.Request, "photo-session")
	session.Values["user_id"] = nil
	session.Save(c.Request, c.Writer)

	c.JSON(http.StatusOK, gin.H{"message": "Logout successful"})
}
